<template>
  <!--弹出窗-->
  <modal ref="modal_1"
         :title="title"
         :isCloseConfirm="this.editable"
         :fullscreen="this.fullscreen"
         top="5%"
         width="50%"
         :close-on-click-modal="true"
         @modalOpened="opened"
         @modalClose="closed">

    <avue-form :option="option"
               ref="form"
               v-model="form"
               @submit="onSubmit"
               :upload-before="uploadBefore"
               :upload-after="uploadAfter"

               :upload-exceed="uploadExceed"
               :upload-error="uploadError">
      <template #nodeNo>
        <el-input v-model="form.nodeNo" readonly placeholder="请选择物料" @click="showSelectMaterial"/>
      </template>

      <!--<template #programCode>-->
        <!--<el-select v-model="form.programCode" placeholder="请选择品牌代号" filterable clearable>-->
          <!--<el-option-->
                  <!--v-for="item in customerGroupList"-->
                  <!--:key="item.programCode"-->
                  <!--:label="item.programName"-->
                  <!--:value="item.programCode"-->
          <!--&gt;-->
          <!--</el-option>-->
        <!--</el-select>-->
      <!--</template>-->
    </avue-form>

    <!--底部按钮块, 默认只有"取消"按钮-->
    <template #footerButton>
      <el-button
              type="primary"
              v-if="(permission.bom_list_add || permission.bom_list_edit)"
              :loading="btnLoading"
              @click="this.$refs.form.submit()"
      >保 存
      </el-button>
      <el-button @click="$refs.modal_1.handleClose()">关闭</el-button>
    </template>
    <select-new-material ref="selectMaterial" @success="setMaterial"></select-new-material>
  </modal>
</template>

<script>
    import {getList, getDetail, add, update, remove, getMaterialFront} from "@/api/anwise/material/material";
    import {checkBomChild, checkBom,getByNodeNo, copy} from "@/api/anwise/material/bom_list";
    import {selectCustomerGroup, generatePackLabel} from "@/api/anwise/material/customer_group";
  import {mapGetters} from "vuex";
    import {Pattern} from "@/utils/validate.js";
    import selectNewMaterial from "@/views/anwise/material/components/select_new_material.vue";

  export default {
      components: {
          selectNewMaterial
      },
    data() {
      return {
        emits: ["success"],
          selectedMaterialNo:'',
          customerGroupList:[],
          selectModelList:[],
        editable: false,
        title: "bom资料",
        isCloseConfirm: false,
        fullscreen: false,
        form: {},
        query: {},
        loading: true,
          btnLoading: false,
        option: {
          height: 'auto',
          calcHeight: 30,
          labelWidth: 150,
          menuWidth: 120,
          submitBtn: false,
          emptyBtn: false,
          column: [
              {
                  label: "物料编号",
                  prop: "nodeNo",
                  type: "input",
                  placeholder:"选择物料自动带入",
                  rules: [{
                      required: false,
                      message: "请输入物料编号",
                      trigger: "blur"
                  }],
              },
              {
                  label: "物料名称",
                  prop: "nodeName",
                  type: "input",
                  disabled:true,
                  rules: [{
                      required: true,
                      message: "请输入物料名称",
                      trigger: "blur"
                  }],
              },
              {
                  label: "类别",
                  prop: "type",
                  type: "select",
                  filterable:true,
                  search: true,
                  overHidden: true,
                  sortable: true,
                  disabled:true,
                  dicUrl: "/blade-system/dict-biz/dictionary?code=material_s_type",
                  width:120,
                  props: {
                      label: 'dictValue',
                      value: 'dictKey',
                  },
                  dataType: 'string',
                  rules: [{
                      required: true,
                      message: "请选择类别",
                      trigger: "blur"
                  }],
              },

              {
                  label: "单位用量",
                  prop: "num",
                  type: "input",
                  value:1,
                  rules: [{
                      required: false,
                      message: "请输入单位用量",
                      trigger: "blur"
                  },{
                      pattern: Pattern.number_3,
                      message: '请输入正确的数字',
                      trigger: 'blur',
                  }],
              },
              {
                  label: "单位",
                  prop: "unit",
                  type: "select",
                  filterable:true,
                  dicUrl: '/api/blade-anwise/unit_info/select',
                  props: {
                      label: 'name',
                      value: 'name',
                  },
                  dataType: 'string',
                  value:'PCS',
                  rules: [{
                      required: false,
                      message: "请选择单位",
                      trigger: "blur"
                  }],
              },
              {
                  label: "损耗",
                  prop: "wastage",
                  type: "input",
                  value:'0',
                  rules: [{
                      required: false,
                      message: "请输入单位用量",
                      trigger: "blur"
                  },{
                      pattern: Pattern.number_3,
                      message: '请输入正确的数字',
                      trigger: 'blur',
                  }],
              },
              {
                  label: "备注",
                  prop: "remark",
                  type: "textarea",
                  span: 24,
                  minRows:2,
              },
          ]
          },
          data: []
        };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.material_add, false),
          viewBtn: this.validData(this.permission.material_view, false),
          delBtn: this.validData(this.permission.material_delete, false),
          editBtn: this.validData(this.permission.material_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
      mounted() {
          // this.initDict();
      },
    methods: {
        generatePackLabel(value) {
            if (value) {
                this.form.programCode = value;
                console.log(this.form);
                generatePackLabel(this.form).then(res => {
                    if (res.data.success) {
                        this.form.packLabel = res.data.data || "";
                    }
                }).catch(err => {
                    console.log(err)
                    this.$message({
                        type: "error",
                        message: "获取品牌分组数据异常！"
                    });
                })
            }
        },
          initDict() {
              selectCustomerGroup().then(res => {
                  if (res.data.success) {
                      this.customerGroupList = res.data.data;
                  }
              }).catch(err => {
                  console.log(err)
                  this.$message({
                      type: "error",
                      message: "获取品牌分组数据异常！"
                  });
              })
          },
        setMaterial(data) {
          console.log(data);
            getDetail(data.id).then(res => {
                if (res.data.success) {
                    let data = res.data.data;
                    this.form.nodeName = data.materialName;
                    this.form.nodeNo = data.materialNo;
                    this.form.type = data.type;
                }
            }).catch(err => {
                console.log(err)
                this.$message({
                    type: "error",
                    message: "选择物料时发生异常！"
                });
            })
        },
        setModelInfo(list) {
            console.log(list);
            this.selectModelList = markRaw(list);
            let ids = [];
            let modelNos = [];
            this.selectModelList.forEach(ele => {
                ids.push(ele.id);
                modelNos.push(ele.modelNo)
            });
            console.log("ids",ids);
            console.log("modelNos",modelNos);
            this.form.modelNo = modelNos.join(",");
            this.form.modelId = ids.join(",");
        },
        showSelectMaterial() {
            this.$refs.selectMaterial.showSelect();
        },
        showSelectModel() {
            this.$refs.selectModelInfo.showSelect(this.selectModelList);
        },
        onSubmit(form, done) {
            form.selectedMaterialNo = this.selectedMaterialNo;
            copy(form).then(res => {
                done();
                if (res.data.success) {
                    this.$message({
                        type: "success",
                        message: res.data.msg ||"操作成功!"
                    });
                }
            });
            this.$refs.modal_1.handleClose();
        },
        show(title,materialNo) {
            this.selectedMaterialNo = materialNo;
            getByNodeNo(materialNo).then(rs => {
                if (rs.data.success) {
                    this.form = rs.data.data;
                    this.form.id = "";
                    this.form.nodeNo = "";
                    this.form.nodeName = "";
                    this.form.type = "";
                    console.log(this.form);
                    this.title=title;
                    this.$refs.modal_1.show();
                }
            });
        },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
        opened() {
            console.log("opened")
        },
        closed() {
            this.form={}
        },
        uploadBefore (file, done, loading, column) {
            console.log(file, column)
            // var newFile = new File([file], '1234', { type: file.type });
            done(file)
            // this.$message.success('上传前的方法')
        },
        uploadAfter (res, done, loading, column) {
            console.log(res, column)
            if (!this.form.imgList) {
                this.form.imgList = [];
            }
            this.form.imgList.push(res);
            done()
            this.$message.success('上传成功！')
        },
        uploadDelete (file, column) {
            console.log(file, column)
            return new Promise((resolve, reject) => {
                if (this.form.imgList) {
                    this.form.imgList.forEach(item => {
                        if (item.url === file.url) {
                            console.log("删除项", item.url, file.url);
                            console.log(this.form.imgList.splice(item,1));
                        }
                        console.log(this.form.imgList);
                    })
                }
                resolve();
            });

        },
        uploadExceed (limit, files, fileList, column) {
            console.log(limit, files, fileList, column)
            this.$message.error('超出上传限制文件数量')
        },
        uploadError (error, column) {
            this.$message.error('上传失败！')
            console.log(error, column)
        }
    }
  };
</script>

<style>
</style>
